import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import '../../../common/service/HttpService.dart';

class RegisterController extends GetxController {
  /// 输入框控制器
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  final nicknameController = TextEditingController();
  final phoneController = TextEditingController();
  final phoneCodeController = TextEditingController();

  /// 手机验证码按钮文本
  final getPhoneCode = "获取手机验证码".obs;

  /// 倒计时
  final countdown = 0.obs;

  bool get isCounting => countdown.value > 0;

  Timer? _timer;

  /// 注册
  Future<void> register() async {
    final username = usernameController.text.trim();
    final password = passwordController.text.trim();
    final nickname = nicknameController.text.trim();
    final phone = phoneController.text.trim();
    final phoneCode = phoneCodeController.text.trim();

    // 1️⃣ 表单校验
    final errorMsg = _validateInput(username, password, nickname, phone, phoneCode);
    if (errorMsg != null) {
      EasyLoading.showError(errorMsg);
      return;
    }

    // 2️⃣ 调用接口
    try {
      final response = await HttpService.to.post(
        "/user/register",
        query: {"phoneCode": phoneCode},
        data: {"username": username, "password": password, "nickname": nickname, "phone": phone},
      );

      if (response.statusCode == 200 && response.data["code"] == 200) {
        EasyLoading.showSuccess("注册成功");
        Get.back(); // 返回登录
      } else {
        EasyLoading.showError(response.data["msg"] ?? "注册失败");
      }
    } catch (e) {
      EasyLoading.showError("注册异常: $e");
    }
  }

  /// 表单校验
  String? _validateInput(String username, String password, String nickname, String phone, String phoneCode) {
    if (username.length < 6) return "账号至少 6 位";
    if (!RegExp(r'^[a-zA-Z0-9]+$').hasMatch(username)) return "账号只能包含字母和数字";
    if (password.length < 6) return "密码至少 6 位";
    if (nickname.isEmpty) return "昵称不能为空";
    if (phone.length != 11) return "请输入正确的 11 位手机号";
    if (phoneCode.length != 6) return "请输入 6 位验证码";
    return null;
  }

  /// 发送验证码
  Future<void> sendPhoneCode() async {
    final phone = phoneController.text.trim();
    if (phone.length != 11) {
      EasyLoading.showError("请输入正确的 11 位手机号");
      return;
    }

    try {
      final response = await HttpService.to.get("/user/sendPhoneCode", query: {"phoneNumber": phone});
      if (response.statusCode == 200 && response.data["code"] == 200) {
        startCountdown(60);
        EasyLoading.showSuccess("验证码已发送");
      } else {
        EasyLoading.showError(response.data["msg"] ?? "发送失败");
      }
    } catch (e) {
      EasyLoading.showError("发送验证码异常: $e");
    }
  }

  /// 启动倒计时
  void startCountdown(int seconds) {
    _timer?.cancel();
    countdown.value = seconds;
    _updateButtonText();

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countdown.value--;
      _updateButtonText();
      if (countdown.value <= 0) {
        timer.cancel();
      }
    });
  }

  /// 更新按钮文本
  void _updateButtonText() {
    getPhoneCode.value = isCounting ? "${countdown.value}s后重发" : "获取手机验证码";
  }

  @override
  void onClose() {
    _timer?.cancel();
    usernameController.dispose();
    passwordController.dispose();
    nicknameController.dispose();
    phoneController.dispose();
    phoneCodeController.dispose();
    super.onClose();
  }
}
